<?php
class offerActions extends sfActions {

  public function executeList(sfWebRequest $request) {
    if ($request->getParameter('did')) {
      $offer = OFFERTable::getInstance()->find($request->getParameter('did'));
      $this->forward404Unless($offer instanceof OFFER);
      $offer->setStatus(Constants::STATUS_INACTIVE);
      $offer->save();
      $this->redirect('@offer_list_current');
    }

    try {
      if ($this->getUser()->hasCredential(Constants::USER_GROUP_SUPER_ADMIN)) {
        $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_MERCHANT_ID);
      }
      $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_LAST_SEARCHED_MOVIE);

      $sortBy = $request->hasParameter(sfConfig::get('app_sort_parameter_name')) ? $request->getParameter(sfConfig::get('app_sort_parameter_name')) : OfferForm::SORT_SESSION_TIME;
      switch ($sortBy) {
        case OfferForm::SORT_CINEMA:
          $sortBy = 'c.NAME';
          break;
        case OfferForm::SORT_MOVIE:
          $sortBy = 'm.TITLE';
          break;
        case OfferForm::SORT_FILLED:
          $sortBy = 'FILLED desc';
          break;
        case OfferForm::SORT_SEATS_COUNT:
          $sortBy = 'o.SEATS_COUNT desc';
          break;
        default:
          $sortBy = 'o.' . $sortBy;
          break;
      }

      $pager = new sfDoctrinePager('Offer', sfConfig::get('app_list_records_per_page'));
      $q = Doctrine_Query::create()->select('o.*, c.*, m.*, (((o.SEATS_COUNT-o.SEATS_AVAILABLE_COUNT)/o.SEATS_COUNT)*100) AS FILLED')->from('OFFER o')->leftJoin('o.CINEMA c')->leftJoin('o.MOVIE m')->orderBy($sortBy);
      if ($this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID)) {
        $q->where('c.MERCHANT_ID = ?', $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      }
      if ($request->getParameter('type') == 'current') {
        $q->andWhere('(o.VALID_TO IS NOT NULL AND o.VALID_TO >= ?) OR (o.VALID_TO IS NULL AND o.SESSION_TIME >= ?) OR (o.VALID_TO IS NULL AND o.SESSION_TIME IS NULL)', array(date(Constants::DATE_TIME_MYSQL_DB), date(Constants::DATE_TIME_MYSQL_DB)));
        $this->type = 'Active';
      } elseif ($request->getParameter('type') == 'expired') {
        $q->andWhere('(o.VALID_TO IS NOT NULL AND o.VALID_TO < ?) OR (o.VALID_TO IS NULL AND o.SESSION_TIME < ?)', array(date(Constants::DATE_TIME_MYSQL_DB), date(Constants::DATE_TIME_MYSQL_DB)));
        $q->andWhere('(o.VALID_TO IS NOT NULL AND TIMESTAMPDIFF(day, o.VALID_TO, ?) <= 30) OR (o.VALID_TO IS NULL AND TIMESTAMPDIFF(day, o.SESSION_TIME, ?) <= 30)', array(date(Constants::DATE_TIME_MYSQL_DB), date(Constants::DATE_TIME_MYSQL_DB)));
        $this->type = 'Expired (Past 30 days)';
      }

      if ($request->getParameter(sfConfig::get('app_sort_parameter_name').'2')) {
        $q->andWhere('c.ID = ?', $request->getParameter(sfConfig::get('app_sort_parameter_name').'2'));
      }

      $pager->setQuery($q);
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }

  public function executeAddOffer(sfWebRequest $request) {
    if ($this->getUser()->hasCredential(Constants::USER_GROUP_SUPER_ADMIN)) {
      $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_MERCHANT_ID);
    }
    $errorCollector = array();
    $cinemaId = null;
    if ($request->isMethod('post')) {
      $formData = $request->getParameter(OfferForm::FORM_NAME);
      $cinemaId = $formData[OfferForm::FIELD_CINEMA];
    }    
    $this->form = new OfferForm($cinemaId);
    
    $trans = SystemUtil::beginDoctrineTransaction();

    if ($request->hasParameter('id')) {
      $offer = OFFERTable::getInstance()->find($request->getParameter('id'));
      $this->forward404Unless($offer instanceof OFFER);
      $this->forward404If($this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID) && $offer->getCINEMA()->getMerchantId() != $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      $this->isEdit = true;
      $this->form = new OfferForm($offer->getCinemaId());
      $this->form->populateData($offer);
    } else if ($request->hasParameter('cid')) {
      $offer = OFFERTable::getInstance()->find($request->getParameter('cid'));
      $this->forward404Unless($offer instanceof OFFER);
      $this->forward404If($this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID) && $offer->getCINEMA()->getMerchantId() != $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      $offer = $offer->copy(false);
      $offer->setValidFrom(date(Constants::DATE_TIME_MYSQL_DB));
      $offer->setValidTo(null);
      $offer->setSessionTime(null);
      $this->isCopy = true;
      $this->form->populateData($offer);
    } else {
      $offer = new OFFER();
    }

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(OfferForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {
          
          if (!isset($this->isEdit)) {
            $sessionMovie = $this->getUser()->getAttribute(Constants::SESSION_LAST_SEARCHED_MOVIE);
            
            if ($sessionMovie->is_manual === true) {
              $movie = MOVIETable::getInstance()->find($sessionMovie->primary_id);
            } else {
              $movie = MOVIETable::getInstance()->findOneByRtId($sessionMovie->id);
            }
            
            if (!is_object($movie)) {
              $movie = new MOVIE();

              $posterUrl = null;
              if (isset($sessionMovie->posters->original)) {
                $posterUrl = $sessionMovie->posters->original;
              } else {
                $posterUrl = $sessionMovie->posters->detailed;
              }

              if (!strstr($posterUrl, 'poster_default.gif')) {
                $monviaHttpClient = new MonviaHttpClient(10);
                $monviaHttpClient->get($posterUrl, array());

                if ($monviaHttpClient->isResponseOk()) {
                  $data = $monviaHttpClient->getResponseBody();
                  $extention = strrchr($posterUrl, '.');
                  $fileName = sfConfig::get('sf_upload_dir') . '/' . uniqid() . $extention;
                  if (strlen($data) > 0 && file_put_contents($fileName, $data)) {
                    if (file_exists($fileName) && filesize($fileName) > 0) {
                      $fName = md5(uniqid()) . $extention;
                      $fileName2 = sfConfig::get('sf_upload_dir') . '/posters/' . $fName;
                      ThumbnailGen::resizeImage($fileName, sfConfig::get('app_movie_poster_width'), null, 0, $fileName2, 100);
                      if (!file_exists($fileName2)) {
                        copy($fileName, $fileName2);
                      }
                    }
                    unlink($fileName);
                  }
                } else {
                  throw new Exception('Unable to find the movie poster. Please try again.', -1);
                }
              }

              if (isset($fileName2) && file_exists($fileName2)) {
                $movie->setUrlPoster($fName);
              } else {
                throw new Exception('Unable to find the movie poster.', -1);
                $movie->setUrlPoster(null);
              }
            }

            if (isset($sessionMovie->title)) {
              $movie->setTitle($sessionMovie->title);
            } else {
              throw new Exception('Unable to find the movie title.', -1);
            }

            if (isset($sessionMovie->year)) {
              $movie->setYear($sessionMovie->year);
            } else {
              $movie->setYear(null);
            }

            if (isset($sessionMovie->mpaa_rating)) {
              $movie->setRating($sessionMovie->mpaa_rating);
            } else {
              $movie->setRating(null);
            }

            if (isset($sessionMovie->synopsis)) {
              $movie->setSynopsis($sessionMovie->synopsis);
            } else {
              $movie->setSynopsis(null);
            }

            if (isset($sessionMovie->runtime)) {
              $movie->setRuntime($sessionMovie->runtime);
            } else {
              $movie->setRuntime(null);
            }

            if (isset($sessionMovie->alternate_ids) && isset($sessionMovie->alternate_ids->imdb)) {
              $movie->setImdbId($sessionMovie->alternate_ids->imdb);
            } else {
              $movie->setImdbId(null);
            }

            if (isset($sessionMovie->id)) {
              $movie->setRtId($sessionMovie->id);
            } else {
              $movie->setRtId(null);
            }

            if ($movie->getImdbId()) {
              $movie->setUrlImdb('http://www.imdb.com/title/tt' . $movie->getImdbId());
            } else {
              $movie->setUrlImdb(null);
            }

            if (isset($sessionMovie->links) && isset($sessionMovie->links->alternate)) {
              $movie->setUrlRt($sessionMovie->links->alternate);
            } else {
              $movie->setUrlRt(null);
            }

            $movie->setStatus(Constants::STATUS_ACTIVE);
          } else {
            $movie = $offer->getMOVIE();
          }

          if (!trim($formData[OfferForm::FIELD_MOVIE_TRAILER_URL])) {
            //throw new Exception('Unable to find the movie trailer URL.', -1);
          }
          $movie->setUrlTrailer(($formData[OfferForm::FIELD_MOVIE_TRAILER_URL]) ? $formData[OfferForm::FIELD_MOVIE_TRAILER_URL] : null);
          $movie->save();
          $offer->setMovieId($movie->getId());

          if (!isset($this->isEdit)) {
            $offer->setCode($formData[OfferForm::FIELD_OFFER_CODE]);
            $offer->setCinemaId($formData[OfferForm::FIELD_CINEMA]);
            $offer->setSeatsAvailableCount($formData[OfferForm::FIELD_SEATS_COUNT]);
          }
          $offer->setScreenNumber($formData[OfferForm::FILED_SCREEN_NO]);
          $offer->setSessionTime(($formData[OfferForm::FIELD_SESSION_TIME_D] && OfferForm::convertTimeArray2String($formData[OfferForm::FIELD_SESSION_TIME_T])) ? 
                                    DatetimeUtil::convertDateTZ($formData[OfferForm::FIELD_SESSION_TIME_D] . ' ' . OfferForm::convertTimeArray2String($formData[OfferForm::FIELD_SESSION_TIME_T]), sfConfig::get('sf_default_timezone'), $offer->getCinemaTZ())
                                    : null
                                );
          $offer->setValidFrom(DatetimeUtil::convertDateTZ($formData[OfferForm::FIELD_VALID_FROM_D] . ' ' . OfferForm::convertTimeArray2String($formData[OfferForm::FIELD_VALID_FROM_T]), sfConfig::get('sf_default_timezone'), $offer->getCinemaTZ()));
          $offer->setValidTo(($formData[OfferForm::FIELD_VALID_TO_D] && OfferForm::convertTimeArray2String($formData[OfferForm::FIELD_VALID_TO_T])) ? 
                               DatetimeUtil::convertDateTZ($formData[OfferForm::FIELD_VALID_TO_D] . ' ' . OfferForm::convertTimeArray2String($formData[OfferForm::FIELD_VALID_TO_T]), sfConfig::get('sf_default_timezone'), $offer->getCinemaTZ()): 
                               null
                            );
          $offer->setTicketPrice($formData[OfferForm::FIELD_TICKET_PRICE]);
          $offer->setSeatsCount($formData[OfferForm::FIELD_SEATS_COUNT]);
          $offer->setSeatsFrom(($formData[OfferForm::FIELD_SEATS_FROM]) ? $formData[OfferForm::FIELD_SEATS_FROM]: null);
          $offer->setSeatsTo(($formData[OfferForm::FIELD_SEATS_TO]) ? $formData[OfferForm::FIELD_SEATS_TO]: null);
          //$offer->setCinemaNo(($formData[OfferForm::FIELD_CINEMA_NO]) ? $formData[OfferForm::FIELD_CINEMA_NO]: null);
          $offer->setAdditionalInfo(($formData[OfferForm::FIELD_ADDITIONAL_INFO]) ? $formData[OfferForm::FIELD_ADDITIONAL_INFO]: null);
          $offer->setStatus($formData[OfferForm::FIELD_STATUS]);
          $offer->save();

          SystemUtil::commitDoctrineTransaction($trans);
          $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_LAST_SEARCHED_MOVIE);
          $this->redirect('@offer_list_current');
        }
      }
    } catch (Exception $e) {
      if ($e->getCode() === -1) {
        $errorCollector[] = $e->getMessage();
      } else {
        $errorCollector[] = LangUtil::getText('error_save_failed');
      }
      SystemUtil::rollbackDoctrineTransaction($trans);
    }

    $this->errorCollector = $errorCollector;

    $this->isReadOnly = false;

    if ($request->getParameter('type') == 'expired') {
      $this->isReadOnly = true;
      $this->isExpired = true;
    }

    if (isset($this->isEdit) && strtotime($offer->getValidFrom()) <= time()) {
      $this->isReadOnly = true;
      $this->isActive = true;
    }
    $this->offer = $offer;
  }

  public function executeFetchMovieInfoAjax(sfWebRequest $request) {
    $movie = MOVIETable::getInstance()->findMovieByTitle($request->getParameter('title'));
    if (count($movie) && $movie[0] instanceof MOVIE) {
      
      $movieObj = new stdClass();
      $movieObj->primary_id = $movie[0]->getId();
      $movieObj->title = $movie[0]->getTitle();
      $movieObj->mpaa_rating = $movie[0]->getRating();
      $movieObj->synopsis = $movie[0]->getSynopsis();
      $movieObj->alternate_ids = new stdClass();
      $movieObj->alternate_ids->imdb = $movie[0]->getImdbId();
      $movieObj->id = $movie[0]->getRtId();
      $movieObj->trailer = $movie[0]->getUrlTrailer();
      $movieObj->year = $movie[0]->getYear();
      $movieObj->runtime = $movie[0]->getRuntime();
      $movieObj->links = new stdClass();
      $movieObj->links->alternate = $movie[0]->getUrlRt();
      $movieObj->is_manual = true;
      
      $this->getUser()->setAttribute(Constants::SESSION_LAST_SEARCHED_MOVIE, $movieObj);
      return $this->renderText(json_encode($movieObj));
      
    } else {
      $monviaHttpClient = new MonviaHttpClient();
      $uri = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . sfConfig::get('app_rotten_tomatoes_api_key') . '&q=' . urlencode($request->getParameter('title')) . '&page_limit=1';
      $monviaHttpClient->get($uri, array());

      if ($monviaHttpClient->isResponseOk()) {
        $data = $monviaHttpClient->getResponseBody();
        if ((int) $data->total > 0 && isset($data->movies[0])) {
          $movie = $data->movies[0];

          $channels = array('supertain', 'trailers', 'movieclipsTRAILERS', '');
          foreach ($channels as $channel) {
            $monviaHttpClient2 = new MonviaHttpClient();
            $uri = 'http://gdata.youtube.com/feeds/api/videos/-/' . strtolower(str_replace(' ', '-', trim($movie->title . ' ' . $movie->year))) . '-trailer?max-results=1';
            if ($channel) {
              $uri .= '&author=' . $channel;
            }
            $monviaHttpClient2->get($uri, array());
            $data = $monviaHttpClient2->getResponseBody();

            $trailerUrl = '';
            if ($monviaHttpClient2->isResponseOk() && isset($data->entry->link[0])) {
              $attr = $data->entry->link[0]->attributes();
              $trailerUrl = (string) $attr->href;
              $trailerUrl = trim(str_replace(strstr($trailerUrl, '&'), '', $trailerUrl));
            }

            $movie->trailer = $trailerUrl;
            $movie->is_manual = false;

            if ($trailerUrl) {
              break;
            }
          }

          $this->getUser()->setAttribute(Constants::SESSION_LAST_SEARCHED_MOVIE, $movie);
          return $this->renderText(json_encode($movie));
        } else {
          return $this->renderText('NOT_FOUND');
        }
      } else {
        return $this->renderText('NOT_OK');
      }
    }
  }
  
  public function executeFetchCinemaInfoAjax(sfWebRequest $request) {
    $cinema = CINEMATable::getInstance()->find($request->getParameter('id'));
    $this->forward404Unless($cinema instanceof CINEMA);
    $num_screen = $cinema->getNumScreens();
    $options = '';
    for ($i = 1; $i <= $num_screen; $i++) {
      $options.= '<option value="'.$i.'">'.$i.'</option>'; 
    }
    $text[] = $options;

    $text[] = DatetimeUtil::convertDateTZ(time(), $cinema->getTimeZone(), sfConfig::get('sf_default_timezone'),'G');
    $text[] = (int)DatetimeUtil::convertDateTZ(time(), $cinema->getTimeZone(), sfConfig::get('sf_default_timezone'),'i');
    $text[] = DatetimeUtil::convertDateTZ(time(), $cinema->getTimeZone(), sfConfig::get('sf_default_timezone'),'Y-m-d');
    
    return $this->renderText(implode('|||||', $text));  
  }
  
  public function executeAddMovie(sfWebRequest $request) {
    if ($this->getUser()->hasCredential(Constants::USER_GROUP_SUPER_ADMIN)) {
      $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_MERCHANT_ID);
    }
    $errorCollector = array();
    $this->form = new MovieForm();
    
    $trans = SystemUtil::beginDoctrineTransaction();
    if ($request->hasParameter('mid')) {
      $movie = MOVIETable::getInstance()->find($request->getParameter('mid'));
      $this->forward404Unless($movie instanceof MOVIE);
      $this->isEdit = true;
      $this->form->populateData($movie);
    } else {
      $movie = new MOVIE();
    }

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(MovieForm::FORM_NAME);
        $formFiles = $request->getFiles(MovieForm::FORM_NAME);
        $this->form->bind($formData, $formFiles);

        if ($this->form->isValid()) {
          $fName = $movie->getUrlPoster();
          if ($formFiles[MovieForm::FIELD_URL_POSTER]['tmp_name']) {
            $extention = strrchr($formFiles[MovieForm::FIELD_URL_POSTER]['name'], '.');
            $fileName  = sfConfig::get('sf_upload_dir') . '/' . uniqid() . $extention;
            move_uploaded_file($formFiles[MovieForm::FIELD_URL_POSTER]['tmp_name'], $fileName);
            
            $fName = md5(uniqid()) . $extention;
            $fileName2 = sfConfig::get('sf_upload_dir') . '/posters/' . $fName;
            if (file_exists($fileName2)) {
              unlink($fileName2);
            }
            ThumbnailGen::resizeImage($fileName, sfConfig::get('app_movie_poster_width'), null, 0, $fileName2, 100);
            if (!file_exists($fileName2)) {
              copy($fileName, $fileName2);
            }
            unlink($fileName);
          }
          
          $movie->setTitle($formData[MovieForm::FIELD_TITLE]);
          $movie->setRating($formData[MovieForm::FIELD_RATING]);
          $movie->setSynopsis($formData[MovieForm::FIELD_SYNOPSIS]);
          $movie->setUrlPoster($fName);
          $movie->setUrlImdb($formData[MovieForm::FIELD_URL_IMDB]);
          $movie->setImdbId(null);
          if (!empty($formData[MovieForm::FIELD_URL_IMDB])) {
            @list($url1, $url2) = explode('title/tt', $formData[MovieForm::FIELD_URL_IMDB]);
            if (isset($url2)) {
              @list($imdbId, $tmp) = explode('/', $url2);
              $movie->setImdbId($imdbId);
            } else {
              $movie->setImdbId(null);
            }
          }
          $movie->setUrlRt($formData[MovieForm::FIELD_URL_RT]);
          $movie->setUrlTrailer($formData[MovieForm::FIELD_URL_TRAILER]);
          $movie->setStatus(Constants::STATUS_ACTIVE);
          $movie->setRuntime(null);
          $movie->setRtId(null);
          $movie->save();
          
          SystemUtil::commitDoctrineTransaction($trans);
          $this->redirect('@movie_list');
        }
      }
    } catch (Exception $e) {
      if ($e->getCode() === -1) {
        $errorCollector[] = $e->getMessage();
      } else {
        $errorCollector[] = LangUtil::getText('error_save_failed');
      }
      SystemUtil::rollbackDoctrineTransaction($trans);
    }

    $this->errorCollector = $errorCollector;
    $this->movie = $movie;
  }
  
  public function executeListMovie(sfWebRequest $request) {
    
    if ($request->getParameter('dmid')) {
      $movie = MOVIETable::getInstance()->find($request->getParameter('dmid'));
      $this->forward404Unless($movie instanceof MOVIE);
      $movie->setStatus(Constants::STATUS_INACTIVE);
      $movie->save();
      $this->redirect('@movie_list');
    }

    try {
      if ($this->getUser()->hasCredential(Constants::USER_GROUP_SUPER_ADMIN)) {
        $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_MERCHANT_ID);
      }

      $sortBy = 'm.TITLE';
      $pager = new sfDoctrinePager('Movie', sfConfig::get('app_list_records_per_page'));
      $q = Doctrine_Query::create()->select('m.*')->from('MOVIE m')->orderBy($sortBy);
      $q->where('m.STATUS = ?', Constants::STATUS_ACTIVE);
      $q->andWhere('m.RT_ID IS NULL');
      
      $pager->setQuery($q);
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }
}